<template>
  <el-dialog v-model="dialogVisible" title="导入" width="500" :close-on-click-modal="false">
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      drag
      :action="props.action"
      multiple
      :auto-upload="false"
      :on-success="handleSuccess"
      :headers="headers"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖动文件或者 <em>点击上传</em></div>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="isLoading"> 确定 </el-button>
      </div>
    </template>

    <div
      v-if="props.templateCode"
      style="color: red; text-decoration: underline; cursor: pointer"
      :href="templateUrl"
      @click="handleDownload"
    >
      下载导入模板
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watchEffect } from "vue";
import { ElDialog, ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";
import { getDetailByCodeApi } from "@/api/system/attchmentManage";
import { downloadFile } from "@/utils/tool";
const props = defineProps(["action", "templateCode", "filename"]);
const emit = defineEmits(["done"]);
const uploadRef: any = ref(null);

const isLoading = ref(false);

const dialogVisible = ref(false);

const templateUrl = ref("");

function handleConfirm() {
  isLoading.value = true;
  uploadRef.value?.submit();
}

function handleSuccess({ data, code }: any) {
  if (!data) {
    data = "导入失败!!!";
  }
  isLoading.value = false;
  ElMessageBox.alert(data, {
    callback() {
      emit("done");
    },
  });
  dialogVisible.value = false;
}

function init() {
  dialogVisible.value = true;
  uploadRef.value?.clearFiles();
}

async function handleDownload() {
  let { data } = await getDetailByCodeApi(props.templateCode);
  data = data?.url;
  if (data) {
    downloadFile(data, props.filename ? props.filename : "模板");
  }
}

defineExpose({
  init,
});

const headers = { Authorization: "Bearer " + getToken() };
</script>
